package com.shensi.adminCollect.controller.station;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shensi.adminCollect.common.constant.HttpStatus;
import com.shensi.adminCollect.common.constant.UserConstants;
import com.shensi.common.core.controller.BaseController;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.page.TableDataInfo;
import com.shensi.common.redis.service.RedisCache;
import com.shensi.adminCollect.common.utils.StringUtils;
import com.shensi.adminCollect.domain.station.Station;
import com.shensi.adminCollect.domain.station.StationOillGun;
import com.shensi.adminCollect.domain.station.WxMessageTemplate;
import com.shensi.adminCollect.domain.station.dto.OmeterGunDto;
import com.shensi.adminCollect.domain.station.dto.StationOilGunDto;
import com.shensi.adminCollect.domain.station.form.StationOillGunPriceForm;
import com.shensi.adminCollect.service.station.IStationOillGunService;
import com.shensi.adminCollect.service.station.IStationService;
import com.shensi.adminCollect.task.station.SaticScheduleTask;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.common.core.domain.entity.SysUser;
/**
 * 油站信息Controller
 *
 * @author qujia
 * @date 2020-12-08
 */
@Api("油枪管理")
@RestController
@RequestMapping("/stationOillGun/info")
public class StationOillGunController extends BaseController
{
    @Autowired
    private IStationOillGunService stationOillGunService;

    @Autowired
    private IStationService stationService;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    public RedisTemplate redisTemplate;


    @Autowired
    private SaticScheduleTask saticScheduleTask;

    /**
     * 查询油站信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(StationOillGun stationOillGun)
    {
        LoginUser loginUser=SecurityUtils.getLoginUser();

        startPage();
        stationOillGun.setDeleteStatus("0");
        //将地址和图片转为string
        String name="";
        if("1".equals(loginUser.getUser().getUserLevel())){
            Station station=new Station();
            station.setEnterpriseId(loginUser.getUser().getEnterpriseId());
            List<Station> stations=stationService.selectStationList(station);
            List<String> ids=new ArrayList<>();
            if(stations!=null&&stations.size()>0){
                for(Station  station2:stations){
                    ids.add(station2.getStationId()+"");
                }
                stationOillGun.setStationIdList(ids);
            }
        }else if("2".equals(loginUser.getUser().getUserLevel())){
            stationOillGun.setStationId(loginUser.getUser().getStationId());
        }else {

        }
        if (stationOillGun.getGunNameList() !=null&&stationOillGun.getGunNameList().length>0) {
            for (String regionData : stationOillGun.getGunNameList()) {
                if ("".equals(name)) {
                    name += regionData;
                } else {
                    name += "," + regionData;
                }
            }

            if (!"".equals(name)) {
                stationOillGun.setGunName(name);
            }
        }
        startPage();
        List<StationOillGun> stationOillGunList = stationOillGunService.selectStationOillGunList(stationOillGun);
        List<StationOillGun> stationOillGunList1=new ArrayList<>();
        for(int mm=0;mm<stationOillGunList.size();mm++){
            if(stationOillGunList.get(mm).getGunName()!=null){
                stationOillGunList.get(mm).setGunNameList(stationOillGunList.get(mm).getGunName().split(","));
            }

        }

        return getDataTable(stationOillGunList);
    }


    /**
     * 查询油站信息列表
     */
    @GetMapping("/gzhList")
    public TableDataInfo gzhList(StationOillGun stationOillGun)
    {
        stationOillGun.setDeleteStatus("0");
        List<StationOillGun> stationOillGunList = stationOillGunService.selectStationOillGunList(stationOillGun);
        return getDataTable(stationOillGunList);
    }


    /**
     * 通过油站id获取抢号信息
     */
    @ApiOperation("通过油站id获取抢号信息")
    @ApiImplicitParam(name = "stationId", value = "油站ID", required = true, dataType = "Long", paramType = "path")
    @GetMapping("/oilGun/{stationId}")
    public AjaxResult listByStationId(@PathVariable("stationId") Long stationId)
    {
        StationOillGun stationOillGun=new StationOillGun();
        stationOillGun.setDeleteStatus("0");
        stationOillGun.setStationId(stationId);
        List<StationOillGun> stationOillGunList = stationOillGunService.selectStationOillGunList(stationOillGun);
        List<String> gunList=new ArrayList<>();
        List<Long> gunnumber=new ArrayList<>();

        for(StationOillGun stationOillGun1:stationOillGunList){
            if(stationOillGun1.getGunName()!=null){
                String[] gun=stationOillGun1.getGunName().split(",");
                for (String mess:gun){
                    gunList.add(mess);
                    gunnumber.add(Long.parseLong(mess));
                }
            }
        }
        Long[] value=new Long[gunnumber.size()];
        for(int ss=0;ss<gunnumber.size();ss++){
            value[ss]=gunnumber.get(ss);
        }
        Long temp=Long.parseLong("0");
        for(int i=0;i<value.length;i++) {
            for (int m = i+1; m < value.length; m++) {
                if(value[i]>value[m]){
                    temp=value[m];
                    value[m]=value[i];
                    value[i]=temp;
                }
            }
        }
        List<String> gunList1=new ArrayList<>();
        for(Long mm:value){
            gunList1.add(mm+"");
        }
        return AjaxResult.success(gunList1);
    }

    @GetMapping("/ometer/oilGun")
    public AjaxResult getOilGun(@RequestParam Long stationId){
        StationOillGun stationOillGun=new StationOillGun();
        stationOillGun.setDeleteStatus("0");
        stationOillGun.setStationId(stationId);
        List<StationOillGun> stationOillGunList = stationOillGunService.selectStationOillGunList(stationOillGun);
        List<OmeterGunDto> ometerGunDtoList = new ArrayList<>();
        stationOillGunList.stream().forEach(stationOil -> {
            String[] strings = stationOil.getGunName().split(",");
            for (String string : strings) {
                OmeterGunDto ometerGunDto = new OmeterGunDto();
                ometerGunDto.setGunNum(string);
                ometerGunDto.setOilName(stationOil.getOilName());
                ometerGunDto.setOilClass(stationOil.getOilClass());
                ometerGunDto.setOilType(stationOil.getOilType());
                ometerGunDtoList.add(ometerGunDto);
            }
        });
        return AjaxResult.success(ometerGunDtoList);
    }

    /**
     * 新增油品
     */
    @PostMapping
    public AjaxResult add(@RequestBody StationOillGun stationOillGun)
    {

        if(stationOillGun.getStationId()==null&&stationOillGun.getOilId()==null){
            return     toAjax(0);
        }
        StationOillGun stationOillGun1=new StationOillGun();
        stationOillGun1.setStationId(stationOillGun.getStationId());
        stationOillGun1.setOilId(stationOillGun.getOilId());
        stationOillGun1.setDeleteStatus("0");
        if(stationOillGunService.selectStationOillGunList(stationOillGun1).size()>0){
            return AjaxResult.error("只允许有一种油品");
        }
        String regionData1="";
        if (stationOillGun.getGunNameList() !=null&&stationOillGun.getGunNameList().length>0) {
            for (String regionData : stationOillGun.getGunNameList()) {
                if ("".equals(regionData1)) {
                    regionData1 += regionData;
                } else {
                    regionData1 += "," + regionData;
                }
            }

            if (!"".equals(regionData1)) {
                stationOillGun.setGunName(regionData1);
            }
        }else {
            return AjaxResult.error("枪号不能为空");

        }
        stationOillGun1.setOilId(null);
        List<StationOillGun> stationOillGunList=stationOillGunService.selectStationOillGunList(stationOillGun1);
        if(stationOillGunList !=null&&stationOillGunList.size()>0){
            for(StationOillGun stationOillGun2:stationOillGunList){
                String gun[]=stationOillGun2.getGunName().split(",");
                for(String  gunname:gun){
                    for(String newGun: stationOillGun.getGunNameList()){
                        if(gunname.equals(newGun)){
                            return AjaxResult.error("抢号已添加油品");
                        }
                    }
                }

            }
        }

        if(stationOillGun.getStationId()!=null){
            Iterator<String> it = redisCache.keys ("price:"+ stationOillGun.getStationId()+":*").iterator ();
            while (it.hasNext ()) {
                String key = it.next ();
                System.out.println(key);
                //清空缓存中记录的数据
                redisCache.deleteObject(key);
            }
        }

        //更新油站修改时间
        Station updateStation = new Station();
        updateStation.setStationId(stationOillGun.getStationId());
        stationService.updateStation(updateStation);
        return toAjax(stationOillGunService.insertStationOillGun(stationOillGun));
    }
    /**
     * 逻辑删除
     */
    @PostMapping(value = "/deleteStationOilGun")
    public AjaxResult deleteStationOilGun(@RequestBody StationOillGun stationOillGun)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        StationOillGun stationOillGun1=new StationOillGun();
        stationOillGun1.setGunId(stationOillGun.getGunId());
        stationOillGun1.setDeleteDate(new Date());
        stationOillGun1.setDeleteStatus("1");
        stationOillGun1.setDeleteUser(currentUser.getUser().getUserId());
        if(stationOillGun.getStationId()!=null){
            Iterator<String> it = redisCache.keys ("price:"+ stationOillGun.getStationId()+":*").iterator ();
            while (it.hasNext ()) {
                String key = it.next ();
                System.out.println(key);
                //清空缓存中记录的数据
                redisCache.deleteObject(key);
            }
        }
        //更新油站修改时间
        Station updateStation = new Station();
        updateStation.setStationId(stationOillGun.getStationId());
        stationService.updateStation(updateStation);
        stationOillGun1.setUpdatedTime(new Date());
        return toAjax(stationOillGunService.updateStationOillGun(stationOillGun1));
    }

    /**
     * 获取油站信息详细信息
     */
    @GetMapping(value = "/{gunId}")
    public AjaxResult getInfo(@PathVariable("gunId") Long gunId)
    {
        StationOillGun stationOillGun=stationOillGunService.selectStationOillGunById(gunId);
        if(stationOillGun.getGunName()!=null){
            stationOillGun.setGunNameList(stationOillGun.getGunName().split(","));
        }
        return AjaxResult.success(stationOillGun);
    }

    /**
     * 修改油站信息
     */
    @ApiOperation("生效时间更新价格")
    @ApiImplicitParam(name = "stationOillGun", value = "油站",  dataType = "StationOillGun")
    @PutMapping
    public AjaxResult edit(@RequestBody StationOillGun stationOillGun)
    {
        LoginUser loginUser=SecurityUtils.getLoginUser();
        Long stationid = loginUser.getUser().getStationId();
        Long enterpriseid = loginUser.getUser().getEnterpriseId();

        if(enterpriseid!=null){
            List<Long> stationidList = stationOillGunService.queryStationIdByEnterpriseId(enterpriseid);
            if(stationid!=null&&!stationid.equals(stationOillGun.getStationId())){
                return AjaxResult.error("只允许修改本站油品价格");
            }
            if(stationid==null&&!stationidList.contains(stationOillGun.getStationId())){
                return AjaxResult.error("只允许修改本站油品价格");
            }
        }else{
            return AjaxResult.error("只允许修改本站油品价格");
        }
//        if(stationid!=stationOillGun.getStationId()){
//            return AjaxResult.error("只允许修改本站油品价格");
//        }
        StationOillGun stationOillGun1=new StationOillGun();
        stationOillGun1.setStationId(stationOillGun.getStationId());
        String regionData1="";
        StationOillGun stationOillGun3=new StationOillGun();
        stationOillGun3.setStationId(stationOillGun.getStationId());
        stationOillGun3.setOilId(stationOillGun.getOilId());
        stationOillGun3.setDeleteStatus("0");
        List<StationOillGun> stationOillGunList1=stationOillGunService.selectStationOillGunList(stationOillGun3);
        if(stationOillGunList1!=null&&stationOillGunList1.size()>0){
            if(stationOillGunList1.get(0).getGunId().equals(stationOillGun.getGunId())){

            }else {
                return AjaxResult.error("只允许有一种油品");
            }
        }
        if (stationOillGun.getGunNameList() !=null&&stationOillGun.getGunNameList().length>0) {
            for (String regionData : stationOillGun.getGunNameList()) {
                if ("".equals(regionData1)) {
                    regionData1 += regionData;
                } else {
                    regionData1 += "," + regionData;
                }
            }

            if (!"".equals(regionData1)) {
                stationOillGun.setGunName(regionData1);
            }
        }
        stationOillGun1.setOilId(null);
        stationOillGun1.setDeleteStatus("0");
        List<StationOillGun> stationOillGunList=stationOillGunService.selectStationOillGunList(stationOillGun1);
        if(stationOillGunList !=null&&stationOillGunList.size()>0){
            for(StationOillGun stationOillGun2:stationOillGunList) {
                if (stationOillGun2.getGunId().equals( stationOillGun.getGunId())) {


                } else {
                    String gun[] = stationOillGun2.getGunName().split(",");
                    for (String gunname : gun) {
                        for (String newGun : stationOillGun.getGunNameList()) {
                            if (gunname.equals(newGun)) {
                                return AjaxResult.error("抢号已添加油品");
                            }
                        }
                    }

                }
            }
        }
        if(stationOillGun.getStationId()!=null){
            Iterator<String> it = redisCache.keys ("price:"+ stationOillGun.getStationId()+":*").iterator ();
            while (it.hasNext ()) {
                String key = it.next ();
                System.out.println(key);
                //清空缓存中记录的数据
                redisCache.deleteObject(key);
            }
        }

        // 油站价格发生变动进行微信模板推送
        StationOillGun oldStationOillGun = stationOillGunService.selectStationOillGunById(stationOillGun.getGunId());
        if (ObjectUtils.notEqual(stationOillGun.getOilStationPrice(), oldStationOillGun.getOilStationPrice())) {
            // 发送模板消息
            Map<String, String> params = new HashMap<>();
            params.put("enterpriseId", String.valueOf(oldStationOillGun.getEnterpriseId()));
            params.put("stationName", oldStationOillGun.getStationName());
            params.put("oilName", oldStationOillGun.getOilName());
            params.put("price", stationOillGun.getOilStationPrice() + "元");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            params.put("date", ObjectUtils.isNotEmpty(stationOillGun.getEffectDate()) ? sdf.format(stationOillGun.getEffectDate()) : sdf.format(new Date()));
            params.put("pushDate", sdf.format(new Date()));
            logger.info("微信模板redis入参：{}", params);
            redisCache.redisTemplate.opsForList().leftPush(WxMessageTemplate.WX_MESSAGE_TEMPLATE_REDIS_KEY, JSONUtil.toJsonStr(params));
        }
        logger.info("生效时间更新价格,请求参数：[{}]",JSONObject.toJSONString(stationOillGun));
        //更新油站修改时间
        Station updateStation = new Station();
        updateStation.setStationId(stationOillGun.getStationId());
        stationService.updateStation(updateStation);

        stationOillGun.setUpdatePriceFlag("N");
        stationOillGun.setUpdatedTime(new Date());
        if(stationOillGun.getEffectDate()!=null){
            List<StationOillGun> stationOillGuntoTemp=null;
            Boolean hasKey = redisTemplate.hasKey("stationOillGuntoTemp");
            if(!hasKey){
                stationOillGuntoTemp = new ArrayList<>();
            }else{
                stationOillGuntoTemp = JSONArray.parseArray(redisCache.getCacheObject("stationOillGuntoTemp"),StationOillGun.class);
            }

            if(stationOillGunService.selectStationOillGunTempById(stationOillGun.getGunId())==null){
                stationOillGunService.updataEffectData(stationOillGun);
                stationOillGuntoTemp = stationOillGuntoTemp.stream().filter(i -> !i.getGunId().equals(stationOillGun.getGunId())).collect(Collectors.toList());
                stationOillGuntoTemp.add(stationOillGun);
                redisCache.setCacheObject("stationOillGuntoTemp", JSON.toJSONString(stationOillGuntoTemp));
                stationOillGunService.insertStationOillGunTemp(stationOillGun);
            }

// 获取当前时间
            Date currentTime = new Date();
            Date effectDate = stationOillGun.getEffectDate();
// 比较时间  立即生效
            if (effectDate.before(currentTime)) {
                return toAjax(stationOillGunService.updateStationOillGun(stationOillGun));
            } else {
                stationOillGunService.updataEffectData(stationOillGun);
               // List<StationOillGun> stationOillGuntoTemp = JSONArray.parseArray(redisCache.getCacheObject("stationOillGuntoTemp");

                stationOillGuntoTemp = stationOillGuntoTemp.stream().filter(i -> !i.getGunId().equals(stationOillGun.getGunId())).collect(Collectors.toList());
                stationOillGuntoTemp.add(stationOillGun);
                redisCache.setCacheObject("stationOillGuntoTemp", JSON.toJSONString(stationOillGuntoTemp));
                // 最后一次修改时间
                StationOillGun updateTime = new StationOillGun();
                updateTime.setUpdatedTime(new Date());
                updateTime.setGunId(stationOillGun.getGunId());
                stationOillGunService.updateStationOillGun(updateTime);
                return toAjax(stationOillGunService.updateStationOillGuntoTemp(stationOillGun));
            }
        }
        return toAjax(stationOillGunService.updateStationOillGun(stationOillGun));
    }

    @ApiOperation(value = "油企账号更新价格", notes = "油企账号更新价格")
    @PutMapping("/updateOilGunPrice")
    public AjaxResult updateStationOillGunPrice(@RequestBody StationOillGunPriceForm stationOillGunPriceForm) {
        stationOillGunService.updateStationOillGunPrice(stationOillGunPriceForm);
        return AjaxResult.success();
    }

    @ApiOperation(value = "小程序更新价格", notes = "小程序更新价格")
    @PutMapping("/smallProgramUpdateOilGunPrice")
    public AjaxResult smallProgramUpdateOilGunPrice(@RequestBody StationOillGunPriceForm stationOillGunPriceForm) {

        stationOillGunService.smallProgramUpdateOilGunPrice(stationOillGunPriceForm);
        return AjaxResult.success();
    }

    @PostMapping("/ometer/oilName")
    @ApiOperation(value = "获取油品",  httpMethod = "POST")
    public AjaxResult getOmeterOilName(@RequestBody Station station){
        if(Objects.isNull(station) || (Objects.isNull(station.getEnterpriseId()) && Objects.isNull(station.getStationId()))){
            //admin 获取所有油品
            StationOilGunDto stationOilGunDto = new StationOilGunDto();
            List<StationOilGunDto> stationOilGunDtos = stationOillGunService.selectStaGunInfoByStationId(stationOilGunDto);
            return AjaxResult.success(stationOilGunDtos);
        }
        List<Long> stationIdList = new ArrayList<>();
        if(Objects.nonNull(station.getEnterpriseId())) {
            // 油企
            List<Station> stationByEnterpriseId = stationService.getStationByEnterpriseId(station.getEnterpriseId());
            if(CollectionUtils.isEmpty(stationByEnterpriseId)){
                return AjaxResult.error("该油企下没有油站");
            }
            stationIdList = stationByEnterpriseId.stream().map(Station::getStationId).collect(Collectors.toList());
            StationOilGunDto stationOilGunDto = new StationOilGunDto();
            stationOilGunDto.setStationIdList(stationIdList);
            List<StationOilGunDto> stationOilGunDtos = stationOillGunService.selectStaGunInfoByStationId(stationOilGunDto);
            return AjaxResult.success(stationOilGunDtos);
        }

        // 油站
        stationIdList.add(station.getStationId());
        StationOilGunDto stationOilGunDto = new StationOilGunDto();
        stationOilGunDto.setStationIdList(stationIdList);
        List<StationOilGunDto> stationOilGunDtos = stationOillGunService.selectStaGunInfoByStationId(stationOilGunDto);
        return AjaxResult.success(stationOilGunDtos);
    }

    @GetMapping("/order/oilGun")
    @ApiOperation(value = "获取当前账号的油枪",  httpMethod = "GET")
    public AjaxResult getOrderOilGun(){

        LoginUser current = SecurityUtils.getLoginUser();
        SysUser sysUser = current.getUser();
        if(Objects.isNull(sysUser)){
            return AjaxResult.error("获取当前账号的油枪，用户不存在");
        }
        List<Long> stationIdList = new ArrayList<>();
        StationOilGunDto stationOilGunDto = new StationOilGunDto();
        List<StationOillGun> stationOilGunDtos = new ArrayList<>();

        if(StringUtils.isEmpty(sysUser.getUserLevel()) || UserConstants.LEVEL_ONE.equals(sysUser.getUserLevel())){
            // admin账号
            stationOilGunDtos = stationOillGunService.selectStationGunInfoOrderOilGun(stationOilGunDto);
            return AjaxResult.success(getStationGuns(stationOilGunDtos));
        }

        if(UserConstants.LEVEL_TWO.equals(sysUser.getUserLevel())){
            // 油企账号
            List<Station> stationByEnterpriseId = stationService.getStationByEnterpriseId(sysUser.getEnterpriseId());
            if(CollectionUtils.isEmpty(stationByEnterpriseId)){
                return AjaxResult.error("该油企下没有油站");
            }
            stationIdList = stationByEnterpriseId.stream().map(Station::getStationId).collect(Collectors.toList());
            stationOilGunDto.setStationIdList(stationIdList);
            stationOilGunDtos = stationOillGunService.selectStationGunInfoOrderOilGun(stationOilGunDto);
            return AjaxResult.success(getStationGuns(stationOilGunDtos));
        }

        if(UserConstants.LEVEL_THREE.equals(sysUser.getUserLevel())){
            // 油站员工账号
            stationIdList.add(sysUser.getStationId());
            stationOilGunDto.setStationIdList(stationIdList);
            stationOilGunDtos = stationOillGunService.selectStationGunInfoOrderOilGun(stationOilGunDto);
            return AjaxResult.success(getStationGuns(stationOilGunDtos));
        }

        return AjaxResult.error("账号不正确");
    }

    private List<Integer> getStationGuns(List<StationOillGun> stationOilGunDtos){
        if(Objects.isNull(stationOilGunDtos)){
            return null;
        }
        List<Integer> gunNums= new ArrayList<>();
        List<String> gunNumList = new ArrayList<>();
        for (StationOillGun stationOilGunDto : stationOilGunDtos) {
            if(StringUtils.isNotEmpty(stationOilGunDto.getGunName())){
                gunNumList.addAll(Arrays.asList(stationOilGunDto.getGunName().split(",")));
            }
        }
        for (String gunNum : gunNumList) {
            if(!gunNums.contains(Integer.valueOf(gunNum))){
                gunNums.add(Integer.valueOf(gunNum));
            }
        }
        Collections.sort(gunNums);
        return gunNums;
    }

    /**
     * 立减活动根据油站选择油品
     * */
    @PostMapping("/discount/oilName")
    @ApiOperation(value = "立减活动根据油站选择油品",  httpMethod = "POST")
    public TableDataInfo discountOilName(@RequestBody StationOilGunDto stationOilGunDto){
        // 请求为空 返回空
        if(Objects.isNull(stationOilGunDto) || CollectionUtils.isEmpty(stationOilGunDto.getStationIdList())){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("请求参数为空");
            rspData.setRows(null);
            rspData.setTotal(0l);
            return rspData;
        }
        logger.info("discountOilName 请求参数：[{}]", JSONObject.toJSONString(stationOilGunDto));
        startPage();
        List<StationOilGunDto> stationOilGunDtos = stationOillGunService.selectStaGunInfoByStationId(stationOilGunDto);
        return getDataTable(stationOilGunDtos);
    }

}
